package com.kaifamiao.controller;

import com.kaifamiao.entity.User;
import com.kaifamiao.exception.ServiceException;
import com.kaifamiao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody User user) {
        log.info( "添加用户" );
        try {
            if(userService.save(user)) {
                return Map.of("success", true, "message", "添加成功" );
            }
            return Map.of("success", false, "message", "添加失败" );
        } catch (ServiceException se) {
            se.printStackTrace();
            return Map.of("success", false, "message", "添加失败", "reason", se.getMessage() );
        }
    }

    @GetMapping("/load/{id}")
    public Map<String,Object> load( @PathVariable("id") Integer id ) {
        log.info( "查询用户" );
        try {
            User user = userService.find(id);
            if( user != null ) {
                return Map.of("success", true, "message", "查询成功", "result", user );
            }
            return Map.of("success", false, "message", "查询失败" , "reason", "数据不存在");
        } catch (ServiceException se) {
            se.printStackTrace();
            return Map.of("success", false, "message", "查询失败", "reason", se.getMessage() );
        }
    }


}
